package mr.ali.videoapp.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import mr.ali.videoapp.portal.Exception.ServiceException;
import mr.ali.videoapp.portal.mapper.CollectionTagMapper;
import mr.ali.videoapp.portal.mapper.CollectionTrailerMapper;
import mr.ali.videoapp.portal.model.CollectionTag;
import mr.ali.videoapp.portal.model.CollectionTrailer;
import mr.ali.videoapp.portal.model.CollectionYurt;
import mr.ali.videoapp.portal.service.ICollectionTrailerService;
import mr.ali.videoapp.portal.service.ICollectionYurtService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Mr-ali
 * @since 2025-06-01
 */
@Service
public class CollectionTrailerServiceImpl extends ServiceImpl<CollectionTrailerMapper, CollectionTrailer> implements ICollectionTrailerService {

    @Resource
    private CollectionTrailerMapper collectionTrailerMapper;

    @Resource
    private CollectionTagMapper collectionTagMapper;

    @Resource
    private ICollectionYurtService collectionYurtService;

    @Override
    public PageInfo<CollectionTrailer> TrailerList(Integer pageNum, Integer pageSize, Integer type, Integer order) {

        // 判断翻页参数是否为空
        if (pageNum == null || pageSize == null) {
            // 抛出翻页参数错误异常
            throw ServiceException.GONE("翻页参数错误");
        }
        // 创建查询条件包装器
        LambdaQueryWrapper<CollectionTrailer> wrapper = new LambdaQueryWrapper<>();
        // 按照创建时间降序排序
        wrapper.eq(CollectionTrailer::getDisplayed, 1);
        if (type != 0) {
            wrapper.eq(CollectionTrailer::getType, type);
        }
        if (order == 1) {
            wrapper.orderByAsc(CollectionTrailer::getId);

        } else {
            wrapper.orderByDesc(CollectionTrailer::getGmtCreate);
        }

        // 使用PageHelper进行分页
        PageHelper.startPage(pageNum, pageSize);
        // 根据查询条件获取视频列表
        List<CollectionTrailer> videoList = collectionTrailerMapper.selectList(wrapper);
        for (CollectionTrailer video : videoList) {
            List<CollectionTag> tag = collectionTagMapper.VideoTrailerSortName(video.getId());
            CollectionYurt yurt = collectionYurtService.findBySortID(video.getYurt());
            video.setYurts(yurt);
            video.setTags(tag);
        }

        return new PageInfo<>(videoList);
    }

}
